package com.bestom.bluetoothlock.bluetooth;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.vectordrawable.graphics.drawable.PathInterpolatorCompat;

import com.bestom.bluetoothlock.LockApplication;
import com.bestom.bluetoothlock.entity.BleInfo;
import com.bestom.bluetoothlock.entity.DeviceInfo;
import com.bestom.bluetoothlock.entity.ReceiveInfo;
import com.bestom.bluetoothlock.util.CurrencyDataManage;
import com.bestom.bluetoothlock.util.DataUtils;
import com.bestom.bluetoothlock.util.LogMsg;
import com.bestom.bluetoothlock.util.LogUtils;
import com.bestom.bluetoothlock.util.SharedPrefrencesHelper;
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;

import java.util.ArrayList;
import java.util.UUID;

public class BlueService extends Service {
    public static String NOTIFI_UUI = "C3E6FEA2-E966-1000-8000-BE99C223DF6A";
    public static String SERVICE_UUID = "C3E6FEA0-E966-1000-8000-BE99C223DF6A";
    private static final String TAG = "agui";
    public static String WRITE_UUID = "C3E6FEA1-E966-1000-8000-BE99C223DF6A";
    public ArrayList<BleInfo> bleInfos = new ArrayList<>();
    BluetoothStateListener bluetoothStateListener = new BluetoothStateListener() {
        public void onBluetoothStateChanged(boolean z) {
            LogUtils.i(BlueService.TAG, "BluetoothStateListener:" + z);
        }
    };
    /* access modifiers changed from: private */
    public DeviceInfo device;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        public void handleMessage(Message message) {
            super.handleMessage(message);
            LogUtils.i(BlueService.TAG, "what:" + message.what);
            if (BlueService.this.handlerListener != null) {
                Message obtain = Message.obtain();
                obtain.obj = message.obj;
                obtain.what = message.what;
                BlueService.this.handlerListener.sendMessage(obtain);
            }
            try {
                switch (message.what) {
                    case 0:
                        LogUtils.i(BlueService.TAG, "foundDevice:" + ((BleInfo) message.obj));
                        return;
                    case 1:
                        boolean unused = BlueService.this.mConnected = ((Boolean) message.obj).booleanValue();
                        return;
                    case 2:
                        DeviceInfo unused2 = BlueService.this.device = (DeviceInfo) message.obj;
                        CurrencyDataManage.getInstance().setCurrenBleDevice(BlueService.this.device);
                        ClientManager.getClient().registerConnectStatusListener(BlueService.this.device.getLockmac(), BlueService.this.mBleConnectStatusListener);
                        BlueService.this.setNotify();
                        return;
                    case 3:
                        return;
                    case 4:
                        if (((Boolean) message.obj).booleanValue()) {
                            LogUtils.i(BlueService.TAG, "ble notify success");
                            if (!LockApplication.getSharedPreferencesHelper().getBoolean("registered_" + CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac())) {
                                BlueService.this.isRegistered = false;
                                return;
                            }
                            BlueService blueService = BlueService.this;
                            blueService.password = LockApplication.getSharedPreferencesHelper().getString("password_" + BlueService.this.device.getLockmac());
                            if (BlueService.this.password != null && BlueService.this.password.length() == 6) {
                                BlueService.this.isRegistered = true;
                                BlueService.this.password_bytes[0] = (byte) Integer.parseInt(BlueService.this.password.substring(0, 2), 16);
                                BlueService.this.password_bytes[1] = (byte) Integer.parseInt(BlueService.this.password.substring(2, 4), 16);
                                BlueService.this.password_bytes[2] = (byte) Integer.parseInt(BlueService.this.password.substring(4, 6), 16);
                                Log.d(BlueService.TAG, String.format("password:%02x%02x%02x", new Object[]{Byte.valueOf(BlueService.this.password_bytes[0]), Byte.valueOf(BlueService.this.password_bytes[1]), Byte.valueOf(BlueService.this.password_bytes[2])}));
                                return;
                            }
                            return;
                        }
                        LogUtils.i(BlueService.TAG, "ble notify fail");
                        return;
                    default:
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    /* access modifiers changed from: private */
    public Handler handlerListener;
    public boolean isRegistered = false;
    /* access modifiers changed from: private */
    public final BleConnectStatusListener mBleConnectStatusListener = new BleConnectStatusListener() {
        public void onConnectStatusChanged(String str, int i) {
            boolean z = i == 16;
            LogMsg.Mess("Connect status :" + z);
            BlueService.this.sendHandlerMsg(1, Boolean.valueOf(z));
        }
    };
    private JTBLEInterface mBleInterface;
    public ConnectStateListen mConnectStateListen;
    /* access modifiers changed from: private */
    public boolean mConnected = false;
    private ArrayList<String> mConnectedDevices = new ArrayList<>();
    private final SearchResponse mSearchResponse = new SearchResponse() {
        public void onSearchStarted() {
            LogMsg.Mess("MainActivity.onSearchStarted");
        }

        public void onDeviceFounded(SearchResult searchResult) {
            if (searchResult != null && searchResult.getName().contains("LOCK")) {
                LogMsg.Mess("\nname:" + searchResult.getName() + "\naddress:" + searchResult.getAddress());
                if (!BlueService.this.peripherals.contains(searchResult)) {
                    BlueService.this.peripherals.add(searchResult);
                    BleInfo bleInfo = new BleInfo();
                    if (LockApplication.getSharedPreferencesHelper().getString("name_" + searchResult.getAddress()).equals("")) {
                        bleInfo.setName(searchResult.getName());
                    } else {
                        bleInfo.setName(LockApplication.getSharedPreferencesHelper().getString("name_" + searchResult.getAddress()));
                    }
                    bleInfo.setAddress(searchResult.getAddress());
                    bleInfo.setRssi(searchResult.rssi);
                    BlueService.this.sendHandlerMsg(0, bleInfo);
                    BlueService.this.bleInfos.add(bleInfo);
                }
            }
        }

        public void onSearchStopped() {
            LogMsg.Mess("onSearchStopped");
        }

        public void onSearchCanceled() {
            LogMsg.Mess("onSearchCanceled");
        }
    };
    public UUID notifiUUID = UUID.fromString("C3E6FEA2-E966-1000-8000-BE99C223DF6A");
    public String password = "";
    public byte[] password_bytes = new byte[3];
    /* access modifiers changed from: private */
    public ArrayList<SearchResult> peripherals = new ArrayList<>();
    public UUID serviceUUID = UUID.fromString("C3E6FEA0-E966-1000-8000-BE99C223DF6A");
    public UUID writeUUID = UUID.fromString("C3E6FEA1-E966-1000-8000-BE99C223DF6A");

    public long byteArrayToLong(byte b, byte b2, byte b3, byte b4) {
        return ((long) ((b2 & 255) << 8)) | ((long) (b & 255)) | ((long) ((b3 & 255) << 16)) | ((long) ((b4 & 255) << 24));
    }

    public boolean isConnented() {
        return this.mConnected;
    }

    public void onCreate() {
        super.onCreate();
        startBLE();
    }

    public int onStartCommand(Intent intent, int i, int i2) {
        return super.onStartCommand(intent, i, i2);
    }

    public void onDestroy() {
        super.onDestroy();
        LogMsg.Mess("BleService destroy");
        disconnect();
        ClientManager.getClient().closeBluetooth();
    }

    @Nullable
    public IBinder onBind(Intent intent) {
        return new LocalBinder();
    }

    private void startBLE() {
        if (!ClientManager.getClient().isBluetoothOpened()) {
            ClientManager.getClient().openBluetooth();
        }
        ClientManager.getClient().registerBluetoothStateListener(this.bluetoothStateListener);
    }

    public void scanLeDevice(boolean z) {
        if (z) {
            this.peripherals.clear();
            this.bleInfos.clear();
            ClientManager.getClient().search(new SearchRequest.Builder().searchBluetoothLeDevice(PathInterpolatorCompat.MAX_NUM_POINTS, 5).build(), this.mSearchResponse);
            return;
        }
        ClientManager.getClient().stopSearch();
    }

    public void connect(final String str) {
        if (this.mConnected) {
            disconnect();
        }
        Log.d(TAG, "connect:" + str);
        ClientManager.getClient().registerConnectStatusListener(str, this.mBleConnectStatusListener);
        ClientManager.getClient().connect(str, new BleConnectOptions.Builder().setConnectRetry(3).setConnectTimeout(30000).setServiceDiscoverRetry(3).setServiceDiscoverTimeout(20000).build(), new BleConnectResponse() {
            public void onResponse(int i, BleGattProfile bleGattProfile) {
                if (i == 0) {
                    LogMsg.Mess("Connect success");
                    Log.d(BlueService.TAG, "connect success!");
                    DeviceInfo deviceInfo = new DeviceInfo();
                    deviceInfo.setLockmac(str);
                    BlueService.this.sendHandlerMsg(2, deviceInfo);
                }
            }
        });
    }

    public void connect(final DeviceInfo deviceInfo) {
        if (this.mConnected) {
            disconnect();
        }
        String lockmac = deviceInfo.getLockmac();
        Log.d(TAG, "connect mac:" + lockmac);
        ClientManager.getClient().registerConnectStatusListener(lockmac, this.mBleConnectStatusListener);
        ClientManager.getClient().connect(lockmac, new BleConnectOptions.Builder().setConnectRetry(3).setConnectTimeout(30000).setServiceDiscoverRetry(3).setServiceDiscoverTimeout(20000).build(), new BleConnectResponse() {
            public void onResponse(int i, BleGattProfile bleGattProfile) {
                if (i == 0) {
                    LogMsg.Mess("Connect success");
                    Log.d(BlueService.TAG, "connect success!");
                    BlueService.this.sendHandlerMsg(2, deviceInfo);
                }
            }
        });
    }

    public void disconnect() {
        if (this.mConnected) {
            LogUtils.i(TAG, "DisConnect");
            ClientManager.getClient().disconnect(CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac());
            ClientManager.getClient().clearRequest(CurrencyDataManage.getInstance().getCurrentBleDevice().getLockmac(), 0);
        }
    }

    public boolean checkBLEenable() {
        return ClientManager.getClient().openBluetooth();
    }

    public void write(final byte[] bArr) {
        if (isConnented() && bArr != null && this.device != null) {
            if (this.isRegistered) {
                int i = 0;
                int i2 = 0;
                while (i < bArr.length) {
                    if (i2 == 3) {
                        i2 = 0;
                    }
                    bArr[i] = (byte) (bArr[i] ^ this.password_bytes[i2]);
                    i++;
                    i2++;
                }
            }
            ClientManager.getClient().write(this.device.getLockmac(), this.serviceUUID, this.writeUUID, bArr, new BleWriteResponse() {
                public void onResponse(int i) {
                    if (i == 0) {
                        if (BlueService.this.isRegistered) {
                            int i2 = 0;
                            int i3 = 0;
                            while (i2 < bArr.length) {
                                if (i3 == 3) {
                                    i3 = 0;
                                }
                                bArr[i2] = (byte) (bArr[i2] ^ BlueService.this.password_bytes[i3]);
                                i2++;
                                i3++;
                            }
                        }
                        Log.d(BlueService.TAG, "发送指令成功:" + StringOper.bytesToHexString(bArr));
                    }
                }
            });
        }
    }

    /* access modifiers changed from: private */
    public void setNotify() {
        if (this.device != null) {
            ClientManager.getClient().notify(this.device.getLockmac(), this.serviceUUID, this.notifiUUID, new BleNotifyResponse() {
                public void onNotify(UUID uuid, UUID uuid2, byte[] bArr) {
                    String str;
                    if (bArr != null && bArr.length > 4) {
                        Log.d(BlueService.TAG, "蓝牙返回的数据：" + StringOper.bytesToHexString(bArr));
                        if (BlueService.this.isRegistered) {
                            int i = 0;
                            int i2 = 0;
                            while (i < bArr.length) {
                                if (i2 == 3) {
                                    i2 = 0;
                                }
                                bArr[i] = (byte) (bArr[i] ^ BlueService.this.password_bytes[i2]);
                                i++;
                                i2++;
                            }
                            Log.d(BlueService.TAG, "蓝牙返回的数据after：" + StringOper.bytesToHexString(bArr));
                        }
                        if (!StringOper.isVerify(bArr)) {
                            Log.e(BlueService.TAG, "无效的数据verify失败");
                        }
                        if (StringOper.toHexString(bArr[0]).equals("a1")) {
                            ReceiveInfo receiveInfo = new ReceiveInfo();
                            String hexString = StringOper.toHexString(bArr[1]);
                            String hexString2 = StringOper.toHexString(bArr[3]);
                            receiveInfo.setCmd(hexString);
                            receiveInfo.setResult(hexString2);
                            if (hexString.equals(BraceletInstructions.INSTRUCTIONS_CHANGE_LOCK_STATE)) {
                                if (hexString2.equals(BraceletInstructions.INSTRUCTIONS_CHANGE_LOCK_STATE)) {
                                    BlueService.this.device.setOpen(true);
                                } else if (hexString2.equals("00")) {
                                    BlueService.this.device.setOpen(false);
                                }
                                CurrencyDataManage.getInstance().setCurrenBleDevice(BlueService.this.device);
                                str = hexString2;
                            } else if (hexString.equals(BraceletInstructions.INSTRUCTIONS_POWER)) {
                                str = StringOper.toHexString(bArr[5]) + StringOper.toHexString(bArr[4]);
                            } else if (hexString.equals(BraceletInstructions.INSTRUCTIONS_FINGER_REGISTER_RESULT)) {
                                receiveInfo.setId(StringOper.toHexString(bArr[4]));
                                str = StringOper.toHexString(bArr[5]);
                            } else {
                                if (hexString.equals("0c")) {
                                    receiveInfo.setId(StringOper.toHexString(bArr[4]));
                                } else if (hexString.equals(BraceletInstructions.INSTRUCTIONS_FINGER_NUMBER) || hexString.equals(BraceletInstructions.INSTRUCTIONS_BLE_STRENGTH)) {
                                    str = StringOper.toHexString(bArr[4]);
                                } else if (hexString.equals(BraceletInstructions.INSTRUCTIONS_GET_RECORD)) {
                                    str = BlueService.this.bytesToHexString(bArr);
                                } else if (hexString.equals(BraceletInstructions.INSTRUCTIONS_SYNC_TIME)) {
                                    long byteArrayToLong = BlueService.this.byteArrayToLong(bArr[3], bArr[4], bArr[5], bArr[6]) * 1000;
                                    Log.d(BlueService.TAG, "sync long:" + byteArrayToLong);
                                    Log.d(BlueService.TAG, "sync time:" + DataUtils.transformTime5(byteArrayToLong));
                                } else if (hexString.equals(BraceletInstructions.INSTRUCTIONS_SET_PASSWORD) && hexString2.equals("00")) {
                                    BlueService.this.isRegistered = true;
                                }
                                str = null;
                            }
                            Log.d(BlueService.TAG, "cmd:" + hexString + "\nresult:" + hexString2 + "\nvalue:" + str);
                            receiveInfo.setValue(str);
                            BlueService.this.sendHandlerMsg(3, receiveInfo);
                            return;
                        }
                        Log.e(BlueService.TAG, "无效的数据");
                    } else if (bArr.length > 0) {
                        if (BlueService.this.isRegistered) {
                            int i3 = 0;
                            int i4 = 0;
                            while (i3 < bArr.length) {
                                if (i4 == 3) {
                                    i4 = 0;
                                }
                                bArr[i3] = (byte) (bArr[i3] ^ BlueService.this.password_bytes[i4]);
                                i3++;
                                i4++;
                            }
                        }
                        Log.e(BlueService.TAG, "无效的数据:" + StringOper.bytesToHexString(bArr));
                    }
                }

                public void onResponse(int i) {
                    if (i == 0) {
                        BlueService.this.sendHandlerMsg(4, true);
                    } else {
                        BlueService.this.sendHandlerMsg(4, false);
                    }
                }
            });
        }
    }

    public String bytesToHexString(byte[] bArr) {
        StringBuilder sb = new StringBuilder("");
        if (bArr == null || bArr.length <= 0) {
            return null;
        }
        for (byte b : bArr) {
            String hexString = Integer.toHexString(b & 255);
            if (hexString.length() < 2) {
                sb.append(0);
            }
            sb.append(hexString);
        }
        return sb.toString();
    }

    public byte[] hexStringToBytes(String str) {
        if (str == null || str.equals("")) {
            return null;
        }
        String upperCase = str.toUpperCase();
        int length = upperCase.length() / 2;
        char[] charArray = upperCase.toCharArray();
        byte[] bArr = new byte[length];
        for (int i = 0; i < length; i++) {
            int i2 = i * 2;
            bArr[i] = (byte) (charToByte(charArray[i2 + 1]) | (charToByte(charArray[i2]) << 4));
        }
        return bArr;
    }

    private byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /* access modifiers changed from: private */
    public void sendHandlerMsg(int i, Object obj) {
        Message message = new Message();
        message.what = i;
        message.obj = obj;
        this.handler.sendMessage(message);
    }

    public final class LocalBinder extends Binder {
        public LocalBinder() {
        }

        public BlueService getService() {
            return BlueService.this;
        }
    }

    public void setHandlerListener(Handler handler2) {
        this.handlerListener = handler2;
    }

    public void setBleInterface(JTBLEInterface jTBLEInterface) {
        this.mBleInterface = jTBLEInterface;
    }

    public void setConnectStateListen(ConnectStateListen connectStateListen) {
        this.mConnectStateListen = connectStateListen;
    }

    public boolean onUnbind(Intent intent) {
        ClientManager.getClient().closeBluetooth();
        return super.onUnbind(intent);
    }
}
